package com.pitaya.winwine.service;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pitaya.framework.common.Constants;
import com.pitaya.framework.common.Encrypt;
import com.pitaya.framework.common.Global;
import com.pitaya.framework.common.StringUtils;
import com.pitaya.winwine.domain.Tag;
import com.pitaya.winwine.domain.User;
import com.pitaya.winwine.repository.TagRepository;
import com.pitaya.winwine.repository.UserRepository;

@Service
public class UserService {

	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private TagRepository tagRepository;
	
	@Transactional
	public void save(User user) {
		Date date = new Date();
		if(user.getId() == null) {
			user.setPassword(DigestUtils.md5Hex(user.getPassword()));
			user.setCreateTime(date);
		}else {
			user.setLastLoginTime(date);
		}
		userRepository.save(user);
	}
	
	@Transactional
	public void addTags(Integer userId, String tags) {
		User user = userRepository.findOne(userId);
		if(StringUtils.isNotBlank(tags)) {
			user.getTags().clear();
			for(String tag : tags.split(",")) {
				user.addTag(new Tag(Integer.parseInt(tag)));
			}
		}
	}
	
	public User login(HttpServletRequest request, HttpServletResponse response, User user) {
		String password = DigestUtils.md5Hex(user.getPassword());
		user = userRepository.findByUsername(user.getUsername());
		if(user != null && user.getPassword().equals(password)) {
			user.setLastLoginTime(new Date());
			userRepository.save(user);
			request.getSession().setAttribute("user", user);
			if (request.getParameter("remember") != null) {
		        Cookie uCookie = new Cookie("winwineu", Encrypt.encryptToDES(Global.key, user.getUsername()));
		        uCookie.setMaxAge(Constants.COOKIE_MAX_AGE);
		        response.addCookie(uCookie);
		        Cookie pCookie = new Cookie("winwineu", Encrypt.encryptToDES(Global.key, password));
		        pCookie.setMaxAge(Constants.COOKIE_MAX_AGE);
		        response.addCookie(pCookie);
			}
			return user;
		}else {
			return null;
		}
	}
	
}
